package cn.yan.luowowo.controller;

import cn.yan.luowowo.annotation.RequireLogin;
import cn.yan.luowowo.cache.service.UserInfoRedisService;
import cn.yan.luowowo.domain.UserInfo;
import cn.yan.luowowo.exception.LogicException;
import cn.yan.luowowo.service.UserInfoService;
import cn.yan.luowowo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("users")
public class UserInfoController {

    //配置属性是在website-api项目中，使用的位置是在trip-core的userserviceimpl中，
    //如果直接将3个属性添加到useriserviceimpl中，mgrsite项目启动时就会报错，
    //原因：mgrsite项目没有这3个配置
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.sign}")
    private String smsSign;
    @Value("${sms.appkey}")
    private String smsAppkey;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoRedisService userInfoRedisService;


    //查询单个用户
    @GetMapping("get")
    public Object get(String id){
        UserInfo userInfo = userInfoService.get(id);
        return userInfo;
    }

    //手机号码校验
    @GetMapping("checkPhone")
    public Object checkPhone(String phone){
        boolean bl=userInfoService.checkPhone(phone);
        return !bl;
    }

    //发送手机验证码
    @GetMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone){
         userInfoService.sendVerifyCode(phone,smsUrl,smsSign,smsAppkey);
        return JsonResult.success();
    }

    //用户注册
    @PostMapping("/regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        return JsonResult.success();

    }

    //用户登录
    @PostMapping("login")
    public Object login(String username,String password){

        //查询该用户
       UserInfo user = userInfoService.login(username,password);
       //token令牌方式：将用户存入redis数据中，key为token的值，value为user对象
        String token = userInfoRedisService.userToken(user);

        //页面需要的数据是token和user的值
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);
       return JsonResult.success(map);

    }

    //浏览器发送的请求
    @RequireLogin     //访问这个方法必须登录才可以访问
    @GetMapping("getCurrentUser")
    public Object getCurrentUser(HttpServletRequest request){

        //获取到请求头中的token
       String token = request.getHeader("token");

       //通过token查询redis中的数据,返回user对象
       UserInfo user = userInfoRedisService.getUserByToken(token);

        return JsonResult.success(user);
    }



}
